package org.wdz.controller;

import ch.ethz.ssh2.Session;
import com.jcraft.jsch.SftpException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.wdz.linuxOperation.RemoteExecuteCommand;
import org.wdz.util.SFTPUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Controller
public class StrangeThingsController {
    private String jarName = "article";
    //首页
    @RequestMapping({"/","/index"})
    public String index(Model model){
        return "index";
    }
    //上传
    @PostMapping("/upload")
    @ResponseBody
    public Map<String,Object> upload(@RequestParam MultipartFile file) throws IOException, SftpException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getContentType());
        System.out.println(file.getSize());
        jarName = file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."));
        System.out.println(jarName);
        File file1 = null;
        file1=File.createTempFile("tmp", null);//创建临时文件
        file.transferTo(file1);
        file1.deleteOnExit();
        FileInputStream in=new FileInputStream(file1);
        String host = "119.29.56.176";
        int port = 22;
        SFTPUtil sftpUtil = new SFTPUtil("root","!wuchuan1258",host,port);
        sftpUtil.login();
        String basePath = "/usr/local/";
        sftpUtil.upload(basePath,"/java",file.getOriginalFilename(),in);
        sftpUtil.logout();
        Map<String,Object> d = new HashMap<>();
        d.put("status",200);
        return d;
    }
    //启动
    @ResponseBody
    @RequestMapping("/startUp")
    public Map<String,Object> startUp(){
        RemoteExecuteCommand remoteExecuteCommand = new RemoteExecuteCommand();
        remoteExecuteCommand.startUp(this.jarName);
        Map<String,Object> d = new HashMap<>();
        d.put("status",200);
        return d;
    }
}
